package com.kalvan.web.servlet.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.kalvan.log.logback.layout.converter.LogPreFixConverter;
import com.kalvan.web.utils.RequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.core.NamedThreadLocal;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 进行接口耗时、接口请求频率统计限制等统计和拦截
 *
 * @author chenliang
 * @version 2018年11月8日
 * @see CallInterfaceInterceptor
 */
@Slf4j
public class CallInterfaceInterceptor extends HandlerInterceptorAdapter {

    private static final ThreadLocal<Long> callInterfaceContextContext = new NamedThreadLocal<Long>(
            "callInterfaceContextContext" );
    public static final ThreadLocal<Map> callContext = new NamedThreadLocal<Map>(
            "callContext" );
    private static final String USER_AGENT = "user-agent" ;

    /**
     * 设置登录账号
     *
     * @param userName
     */
    public static void setUserName(String userName) {
        callContext.get().put("x_username", userName);
    }

    public static void setUserInfo(Object userInfo) {
        callContext.get().put("x_user", userInfo);
    }

    public static String getUserName() {
        return String.valueOf(callContext.get().get("x_username" ));
    }

    public static Object getUserInfo() {
        return callContext.get().get("x_user" );
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        Long start = System.currentTimeMillis();
        callInterfaceContextContext.set(start);
        LogPreFixConverter.resetLogPreFix();
        String msgId = request.getParameter("msgId" );
        if (StringUtils.isNotBlank(msgId)) {
            LogPreFixConverter.setLogPreFix(msgId);
        }
        String ip = RequestUtils.getIpAddr(request);
        String uri = request.getRequestURI();
        log.info("请求地址:{}, ip:{}", uri, ip);
        log.debug("UserAgent:{}", request.getHeader(USER_AGENT));
        log.debug("参数:{}", JSONObject.toJSONString(request.getParameterMap()));
        //初始化context
        callContext.set(new HashMap());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        Long start = callInterfaceContextContext.get();
        super.afterCompletion(request, response, handler, ex);
        Long end = System.currentTimeMillis();
        // TODO 性能测试
        log.info("{}耗时ms:{}", request.getRequestURI(), (end - start));
        LogPreFixConverter.resetLogPreFix();
        callInterfaceContextContext.remove();
        callContext.remove();
    }
}
